<?php
namespace app\web\admin;

use app\common\builder\ZBuilder;
use app\web\model\Banner as BannerModel;

/**
 * 轮播管理（后台）
 * @package
 */
class Banner extends Base {
	/**
	 * 查询
	 * @date   2020-11-06
	 * @return [type]     [description]
	 */
	public function index() {
		$map = $this->getMap();
		$list = BannerModel::alias("a")->where($map)
			->order("a.sort desc,a.id desc")->paginate();

		return ZBuilder::make('table')
			->setTableName('banner')
			->hideCheckbox()
			->addTopButton('add') // 添加顶部按钮
			->addColumns([
				['id', 'ID'],
				['image_id', '图片', 'picture'],
				['sort', '排序', 'text.edit'],
				['update_time', '更新时间', 'datetime'],
				['status', '状态', 'switch'],
				['right_button', '操作', 'btn'],
			])
			->addValidate('Sort', 'sort')
			->setColumnWidth('id,sort,status', 50)
			->addRightButtons(['edit', 'delete' => ['data-tips' => '删除后无法恢复。']])
			->setRowList($list)
			->fetch();
	}
	/**
	 * 修改
	 * @date   2020-11-06
	 * @param  string     $id
	 */
	public function edit($id = '') {
		if ($id === null) {
			$this->error('缺少参数');
		}

		# 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$data['update_time'] = time();
			if(empty($data['image_id'])) $this->error('请上传图片');
			$data['image'] = $this->setImgPath($data['image_id']);
			if (BannerModel::where(['id' => $id])->update($data)) {
				$this->success('编辑成功', url('index'));
			} else {
				$this->error('编辑失败');
			}
		}
		#获取数据，渲染模板
		$data = BannerModel::where('id', $id)->find();
		return ZBuilder::make('form')
			->addImage('image_id', '图片','建议尺寸694*260')
			->addNumber('sort', '排序', "降序, 越大越靠前")
			->addRadio("status", "状态", "", ["1" => "启用", '0' => "禁用"])
			->setFormData($data)
			->fetch();
	}
	/**
	 * 新增
	 * @date   2020-11-06
	 */
	public function add() {
		# 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$data['create_time'] = time();
			$data['update_time'] = time();
			if(empty($data['image_id'])) $this->error('请上传图片');
			$data['image'] = $this->setImgPath($data['image_id']);
			if (BannerModel::create($data)) {
				$this->success('编辑成功', url('index'));
			} else {
				$this->error('编辑失败');
			}
		}

		#获取数据，渲染模板
		return ZBuilder::make('form')
			->addImage('image_id', '图片','建议尺寸694*260')
			->addNumber('sort', '排序', "降序, 越大越靠前", 100)
			->addRadio("status", "状态", "", ["1" => "启用", '0' => "禁用"], 1)
			->fetch();
	}
	/**
	 * 删除
	 */
	public function delete($ids = null, $table = '') {
		if ($ids === null) {
			$this->error('参数错误');
		}

		// 移动文档到回收站
		if (false === BannerModel::where('id', 'in', $ids)->delete()) {
			$this->error('删除失败');
		}
		$this->success('删除成功');
	}

}